package com.example.erp;

import java.util.Map;

import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.transport.ServerParameters;
import io.modelcontextprotocol.client.transport.StdioClientTransport;
import io.modelcontextprotocol.spec.McpSchema.CallToolRequest;
import io.modelcontextprotocol.spec.McpSchema.CallToolResult;
import io.modelcontextprotocol.spec.McpSchema.ListToolsResult;
import io.modelcontextprotocol.spec.McpSchema.TextContent;

/**
 * 使用stdio传输，MCP服务器由客户端自动启动，需要先构建服务器jar并放到指定目录。
 */
public class ClientStdio {

	public static void main(String[] args) {

//		var stdioParams = ServerParameters.builder("java")
//                .args("-Dspring.ai.mcp.server.stdio=true",
//                        "-Dspring.main.web-application-type=none",
//                        "-Dlogging.pattern.console=",
//                        "-jar",
//                        "E:\\\\DevSpringOpen\\\\boot-ai-examples\\\\spring-ai-examples\\\\mcp-server-stdio\\\\target\\\\mcp-server-stdio-0.0.1-SNAPSHOT.jar")
//                .build();

		var stdioParams = ServerParameters.builder("java").args("-jar",
				"E:\\DevSpringAi\\spring-ai-example\\ai-mcp-example\\ai-mcp-server-stdio\\target\\ai-mcp-server-stdio-0.0.1-SNAPSHOT.jar")
				.build();

		var transport = new StdioClientTransport(stdioParams);

		try (var client = McpClient.sync(transport).build()) {
			// 初始化
			client.initialize();

			// 调用工具示例
			ListToolsResult toolsList = client.listTools();
			System.out.println("1-可用的工具集：" + toolsList);
			System.err.println("================================");
			
			CallToolResult sumResult = client.callTool(new CallToolRequest("add", Map.of("a", 1, "b", 2)));
			System.out.println("2-加法计算：1+2 = " + ((TextContent) sumResult.content().get(0)).text());
			System.err.println("================================");
			
			CallToolResult currentTimResult = client.callTool(new CallToolRequest("getCurrentTime", Map.of()));
			System.out.println("3-当前时间：" + ((TextContent) currentTimResult.content().get(0)).text());
			System.err.println("================================");
			
			// 获取北京的天气预报
			CallToolResult weatherForecastResult = client.callTool(new CallToolRequest("getWeatherForecastByLocation",
					Map.of("latitude", "39.9042", "longitude", "116.4074")));
			//System.out.println("4-北京天气预报: " + weatherForecastResult);
			System.out.println("4-北京天气预报: " + ((TextContent) weatherForecastResult.content().get(0)).text());
			System.err.println("================================");
			
			// 获取北京的空气质量信息
			CallToolResult airQualityResult = client.callTool(new CallToolRequest("getAirQuality", 
					Map.of("latitude", "39.9042", "longitude", "116.4074")));
			//System.out.println("5-北京空气质量: " + airQualityResult);
			System.out.println("5-北京空气质量: " + ((TextContent) airQualityResult.content().get(0)).text());

			// close
			client.closeGracefully();
		}
	}

}
